from stark.service.v1 import StarkHandler, StarkModelForm
from django.urls import re_path
from web import models
from  .base import PermissionHandler

class ScoreModelForm(StarkModelForm):
    """自定制积分添加页面字段"""

    class Meta:
        model = models.ScoreRecord
        fields = ['content', 'score']


class ScoreHandler(PermissionHandler,StarkHandler):
    field_name_list = ['student', 'score', ]
    model_form_class = ScoreModelForm

    def get_field_name_list(self,request,*args,**kwargs):
        value = []
        if self.field_name_list:
            value.extend(self.field_name_list)
        return value

    def get_urls(self):
        patterns = [
            re_path('list/(?P<student_id>\d+)/', self.wrapper(self.changelist_view), name=self.get_list_url_name),
            re_path('add/(?P<student_id>\d+)/', self.wrapper(self.add_view), name=self.get_add_url_name),
        ]
        patterns.extend(self.extra_urls())  # 新增的url 扩增
        return patterns

    def get_queryset(self, request, *args, **kwargs):
        student_id = kwargs.get('student_id')
        current_user_id = request.session['current_user_id']
        return self.model_class.objects.filter(student_id=student_id, user_id=current_user_id)

    def save(self, request, form, is_update, *args, **kwargs):
        student_id = kwargs.get('student_id')
        current_user_id = request.session.get('current_user_id')
        # 先保存未显示字段的默认值
        form.instance.student_id = student_id
        form.instance.user_id = current_user_id
        form.save()

        # 对学生列表显示的学生积分 也要同步修改
        # 学生列表显示的积分（原积分）

        # 增加或减少的积分
        score = form.instance.score
        print(score)
        if score > 0:
            form.instance.student.score += abs(score)
        else:
            form.instance.student.score -= abs(score)
        form.instance.student.save()
